package com.puppy.interceptor;


import com.puppy.utils.JWTUtils;
import com.puppy.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求的路径
        String path = request.getRequestURI(); // /login

        //2.判断-是登录则不进行令牌校验，放行其去登录；
        if (path.contains("/login")) {
            log.info("登录请求，放行");
            return true; // 放行,好比Filter的doFilter方法中的chain.doFilter(request, response);
        }

        //3.获取Token
        String token = request.getHeader("token");

        //4.判断token是否存在，token不存在，用户没有登录，返回错误信息401
        if (token == null || token.isEmpty()) {
            log.info("用户未登录，请先登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.setStatus(401);
            return false; // 不放行，返回false
        }
        // 5.token存在，则校验-校验失败401
        try {
            //校验token
            Claims claims=JWTUtils.parseJwt(token);
            //将解析结果的id放到线程变量区
            ThreadLocalUtils.setCurrentLocal(Integer.valueOf(claims.get("id").toString()));
            log.info("令牌校验成功，用户id：{},将其存入ThreadLocal", ThreadLocalUtils.getCurrentLocal());
        } catch (Exception e) {
            log.info("令牌校验失败，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
        //6.校验成功则放行
        log.info("令牌校验成功，放行");
        return true;
    }
}
